# -*- coding: utf-8 -*-
from taobao_category.items import ShopCategoryItem


def parse_detail_item_byxpath(response, items_xpath):
    item_obj = ShopCategoryItem()
    temp = None
    for item in items_xpath:
        detail = item.xpath('dd[contains(@class, "detail")]')
        item_obj['shop_id'] = response.request.meta['shop_id']
        item_obj['title'] = detail.xpath('a/text()').extract()
        item_obj['title'] = item_obj['title'][0].encode('utf-8') if item_obj['title'] else ''

        item_obj['href'] = detail.xpath('a/@href').extract()
        item_obj['href'] = item_obj['href'][0].encode('utf-8') if item_obj['href'] else ''

        item_obj['price'] = detail.xpath(
            'div/div[contains(@class, "cprice-area")]/span[contains(@class, "c-price")]/text()').extract()
        item_obj['price'] = item_obj['price'][0].encode('utf-8') if item_obj['price'] else ''

        item_obj['sales'] = detail.xpath(
            'div/div[contains(@class, "sale-area")]/span[contains(@class, "sale-num")]/text()').extract()
        item_obj['sales'] = item_obj['sales'][0].encode('utf-8') if item_obj['sales'] else ''
        item_obj['evaluation_num'] = item.xpath('dd[contains(@class, "rates")]/div//a/span/text()').extract()
        item_obj['evaluation_num'] = item_obj['evaluation_num'][0].encode('utf-8') if item_obj[
            'evaluation_num'] else ''
        if not item_obj['price'] or not item_obj['sales']:
            continue
        if not temp:
            temp = item_obj
            continue
        try:
            price = float(item_obj['price'])
            sales = int(item_obj['sales'])
            if price < 5:
                continue
            if int(temp['sales']) <= sales:
                temp = item_obj
                continue
        except Exception:
            pass
    return temp